<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
    <meta name="renderer" content="webkit|ie-comp|ie-stand">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
          content="width=device-width,initial-scale=1,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no"/>
    <meta http-equiv="Cache-Control" content="no-siteapp"/>
    <link rel="Bookmark" href="/favicon.ico">
    <link rel="Shortcut Icon" href="/favicon.ico"/>
    <!--[if lt IE 9]>
    <script type="text/javascript" src="lib/html5shiv.js"></script>
    <script type="text/javascript" src="lib/respond.min.js"></script>
    <![endif]-->
    <link rel="stylesheet" type="text/css" href="static/h-ui/css/H-ui.min.css"/>
    <link rel="stylesheet" type="text/css" href="static/h-ui.admin/css/H-ui.admin.css"/>
    <link rel="stylesheet" type="text/css" href="lib/Hui-iconfont/1.0.8/iconfont.css"/>
    <link rel="stylesheet" type="text/css" href="static/h-ui.admin/skin/default/skin.css" id="skin"/>
    <link rel="stylesheet" type="text/css" href="static/h-ui.admin/css/style.css"/>
    <!--[if IE 6]>
    <script type="text/javascript" src="lib/DD_belatedPNG_0.0.8a-min.js"></script>
    <script>DD_belatedPNG.fix('*');</script>
    <![endif]-->
    <title>待配药订单列表</title>
</head>
<style>
    .table > tbody > tr > td {
        text-align: center;
    }
</style>
<body>

<div>
    <nav class="breadcrumb"><i class="Hui-iconfont">&#xe67f;</i> 首页 <span class="c-gray en">&gt;</span> 订单管理 <span
            class="c-gray en">&gt;</span> 待配药订单列表 <a class="btn btn-success radius r"
                                                  style="line-height:1.6em;margin-top:3px"
                                                  href="javascript:location.replace(location.href);" title="刷新"><i
            class="Hui-iconfont">&#xe68f;</i></a></nav>
    <form class="page-container">
        <div class="cl pd-5 bg-1 bk-gray mt-20">
        <span class="l"><a href="javascript:;" onclick="batch_dispenser()" class="btn btn-primary radius"><i
                class="Hui-iconfont">&#xe672;</i> 批量配药</a></span>
            <span style="margin-left: 10px" class="l"><a href="javascript:;" onclick="printReceipt(0)" class="btn btn-success radius"><i
            class="Hui-iconfont">&#xe652;</i> 常温单打印</a></span>
            <span style="margin-left: 10px" class="l"><a href="javascript:;" onclick="printReceipt(1)" class="btn btn-success radius"><i
                    class="Hui-iconfont">&#xe652;</i> 冷链单打印</a></span>
            <span style="margin-left: 10px" class="l"><a href="javascript:;" onclick="printTickets()" class="btn btn-success radius"><i
                    class="Hui-iconfont">&#xe652;</i>打印小票</a></span>
        </div>
        <div class="panel panel-default  mt-20">
            <div class="panel-header">时间筛选</div>
            <div class="panel-body">
                <div class="skin-minimal" id="time-selector">
                    <div class="check-box">
                        <input type="radio" name="time" value="0">
                        <label>所有</label>
                    </div>
                    <div class="check-box">
                        <input type="radio" name="time" value="1" checked>
                        <label>当天</label>
                    </div>
                </div>
            </div>
        </div>

        <div class="panel panel-default  mt-20">
            <div class="panel-header">打印筛选</div>
            <div class="panel-body">
                <div class="skin-minimal" >
                    <div class="check-box">
                        <input type="radio" name="print" value="-1" checked>
                        <label>所有</label>
                    </div>
                    <div class="check-box">
                        <input type="radio" name="print" value="0" >
                        <label>未打印</label>
                    </div>
                    <div class="check-box">
                        <input type="radio" name="print" value="2" >
                        <label>已打印送货单</label>
                    </div>
                    <div class="check-box">
                        <input type="radio" name="print" value="1" >
                        <label>已打印小票</label>
                    </div>
                    <div class="check-box">
                        <input type="radio" name="print" value="3" >
                        <label>都已打印</label>
                    </div>
                </div>
            </div>
        </div>
        <div class="mt-20">
            <div class="mt-20" style="margin-bottom: 70px">
                <table class="table table-border table-bordered table-bg table-hover table-sort" width="100%">
                    <thead>
                    <tr class="text-c">
                        <th width="25"><input type="checkbox" name="" value=""></th>
                        <th width="80">订单号</th>
                        <th width="80">患者姓名</th>
                        <th width="80">联系电话</th>
                        <th width="100">物品清单</th>
                        <th width="60">下单时间</th>
                        <th width="60">预约时间</th>
                        <th width="80">配药地址</th>
                        <th width="100">医保</th>
                        <th width="100">医保类型</th>
                        <th width="100">付款方式</th>
                        <th width="100">备注</th>
                        <th width="100">下单人</th>
                        <th width="40">是否冷链</th>
                        <th width="100">订单状态</th>
                        <th width="50">操作</th>
                    </tr>
                    </thead>
                </table>
            </div>
        </div>
    </form>
</div>

<!--_footer 作为公共模版分离出去-->
<script type="text/javascript" src="lib/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="lib/layer/2.4/layer.js"></script>
<script type="text/javascript" src="static/h-ui/js/H-ui.min.js"></script>
<script type="text/javascript" src="static/h-ui.admin/js/H-ui.admin.js"></script> <!--/_footer 作为公共模版分离出去-->

<!--请在下方写此页面业务相关的脚本-->
<script type="text/javascript" src="lib/datatables/1.10.0/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="lib/datatables/dataTables.colReorder.min.js"></script>
<script type="text/javascript" src="lib/laypage/1.2/laypage.js"></script>
<script type="text/javascript" src="lib/common.js"></script>
<script type="text/javascript" src="lib/LodopFuncs.js"></script>
<script type="text/javascript" src="lib/printer.js"></script>

<script type="text/javascript" src="lib/jr-qrcode.js"></script>
<script type="text/javascript">

    var start = getTodayStart()
    var end = getTodayEnd()

    for (var i = 1;i<5;i++){
        var t = Date.parse(getTodayStart().replace(/-/g, "/"))
        t = t + i*24*60*60*1000
        $('#time-selector').append("<div class=\"check-box\"><input type=\"radio\" name=\"time\" value="+(parseInt(i)+1)+" ><label>"+dateymd(t)+"</label></div>")
    }

    var printState = -1

    $('input[name=state],input[name=time],input[name=print]').change(function (e) {
        radioValue = $('input[name=time]:checked').val()
        switch (radioValue) {
            case '1':
                start = getTodayStart()
                end = getTodayEnd()
                break
            case '0':
                start = ""
                end = ""
                break;
            default :
                console.log(radioValue)
                var t = Date.parse(getTodayStart().replace(/-/g, "/"))
                t = t + (radioValue-1)*24*60*60*1000
                start = dateAll(t)
                var e = Date.parse(getTodayEnd().replace(/-/g, "/"))
                e = e + (radioValue-1)*24*60*60*1000
                end = dateAll(e)
                break;
        }
        printState = $('input[name=print]:checked').val()
        table.destroy()
        table = initTable()
    })


    function initTable(){
        var t = $('.table').DataTable({
            serverSide: true,//开启服务器模式
            "processing": true,//加载显示提示
            "ajax": {
                url: "./order/uncomfired/list",
                type: 'GET',
                data: {
                    "searchKey": "",
                    "minDate": start,
                    "maxDate": end,
                    "state":"10",
                    "isPrint":printState
                }
            },
            "columns": [
                {
                    "data": null,
                    render: function (data, type, row, meta) {
                        return "<input name=\"checkbox\" value=\"" + row.orderId + "\" type=\"checkbox\" value=\"\">";
                    }
                },
                {"data": "orderId"},

                {
                    "data": "receiverName"
                },
                {
                    "data": "receiverPhone"
                },
                {
                    "data": "medicineList",
                    render: function (data, type, row, meta) {
                        var s = ""
                        for (var i = 0;i<data.length;i++){

                            var a ="<span><p>"+data[i].medicineName+data[i].standard +"   数量: "+data[i].num+"</p></span>"
                            s += a;
                        }
                        return s
                    }
                },
                {
                    "data": "createTime",
                    render: function (data, type, row, meta) {
                        return date(data);
                    }
                },
                {
                    "data": "reserveTime",
                    render: function (data, type, row, meta) {
                        return date(data);
                    }
                },
                {
                    "data": "receiverAddress"
                },
                {
                    "data": "insurance"
                },
                {
                    "data": "insuranceType"
                },
                {
                    "data": "paymentType"
                },

                {
                    "data": "prescriptionPic"
                },
                {
                    "data": "memberName"
                },
                {
                    "data": "freezing",
                    render: function (data, type, row, meta) {
                        if (data == 1){
                            return "是"
                        }else{
                            return  "否"
                        }
                    }
                },
                {
                    "data": "status",
                    render: function (data, type, row, meta) {
                        if (data == -1) {
                            return "<span class=\"label label-defant radius td-status\">已取消</span>";
                        } else
                        if (data == 0) {
                            return "<span class=\"label label-defant radius td-status\">待确认</span>";
                        } else if (data == 10) {
                            return "<span class=\"label label-warning radius td-status\">待配药</span>";
                        } else if (data == 20) {
                            return "<span class=\"label label-primary radius td-status\">已配药</span>";
                        } else if (data == 30) {
                            return "<span class=\"label label-secondary radius td-status\">已分配派送员</span>";
                        } else if (data == 40) {
                            return "<span class=\"label label-success radius td-status\">已完成</span>";
                        } else if (data == -10) {
                            return "<span class=\"label label-danger radius td-status\">订单取消</span>";
                        } else {
                            return "<span class=\"label label-warning radius td-status\">其它态</span>";
                        }
                    }
                },
                {
                    "data": null,
                    render: function (data, type, row, meta) {
                        var html = '<button class="btn btn-primary radius" style="margin-bottom: 10px;" type="button" onclick="alert_dispenser(\'' + row.orderId + '\')">配药</button><button class="btn btn-danger radius" type="button" onclick="cancel(\'' + row.orderId + '\')">取消订单</button>';
                        // return "123"
                        html +='<button class="btn btn-secondary radius" style="margin-bottom: 10px;" type="button" onclick="alert_reserve(\'' + row.orderId + '\')">设置预约时间</button>'
                        if (row.freezing == 1){
                            html = '<button class="btn btn-primary radius" style="margin-bottom: 10px;" type="button" onclick="bind_box(\'' + row.orderId + '\')">绑定冰包</button>' +html
                        }
                        return html
                    }
                }
            ],
            "aaSorting": [[1, "desc"]],//默认第几个排序
            "bStateSave": false,//状态保存
            "aoColumnDefs": [
                {"orderable": false, "aTargets": [0]}// 制定列不参与排序
            ],
            language: {
                url: './lib/datatables/Chinese.json'
            },
            colReorder: true
        })
        return t
    }
    var table = initTable()
    /*datatables配置*/


    function batch_dispenser() {
        var cks = document.getElementsByName("checkbox");
        var count = 0, ids = "";
        for (var i = 0; i < cks.length; i++) {
            if (cks[i].checked) {
                count++;
                ids += cks[i].value + ",";
            }
        }
        if (count == 0) {
            layer.msg('您还未勾选任何数据!', {icon: 5, time: 3000});
            return;
        }
        /*去除末尾逗号*/
        if (ids.length > 0) {
            ids = ids.substring(0, ids.length - 1);
        }
        layer.confirm('确认所选的' + count + '条订单已经配药吗？', {icon: 0}, function (index) {
            var index = layer.load(3);
            $.ajax({
                type: 'post',
                url: './order/' + ids+'/dispenser',
                dataType: 'json',
                success: function (data) {
                    layer.close(index);
                    if (data.success != true) {
                        layer.alert(data.message, {title: '错误信息', icon: 2});
                        return;
                    }
                    layer.msg('已完成!', {icon: 1, time: 1000});
                    refresh();
                },
                error: function (XMLHttpRequest) {
                    layer.close(index);
                    layer.alert('数据处理失败! 错误码:' + XMLHttpRequest.status, {title: '错误信息', icon: 2});
                }
            });
        });
    }
    function alert_reserve(id) {
        ORDERID = id
        layer_show("设置时间", "choose-time", 400, 300);
    }
    function setTime(time) {
        $.ajax({
            type: 'post',
            url: './order/' + ORDERID + '/reserve',
            data: {
                reserveTime: time
            },
            dataType: 'json',
            success: function (data) {
                // layer.close(index);
                if (data.success != true) {
                    layer.alert(data.message, {title: '错误信息', icon: 2});
                    return;
                }
                // orderCount();
                refresh();
                layer.msg('设置成功!', {icon: 1, time: 1000});
            },
            error: function (XMLHttpRequest) {
                layer.close(index);
                layer.alert('数据处理失败! 错误码:' + XMLHttpRequest.status, {title: '错误信息', icon: 2});
            }
        });
    }
    function alert_dispenser(orderId) {
        layer.confirm('确认已经配药吗？', {icon: 0}, function (index) {
            var index = layer.load(3);
            $.ajax({
                type: 'post',
                url: './order/' + orderId + '/dispenser',
                dataType: 'json',
                success: function (data) {
                    layer.close(index);
                    if (data.success != true) {
                        layer.alert(data.message, {title: '错误信息', icon: 2});
                        return;
                    }
                    layer.msg('设置成功!', {icon: 1, time: 1000});
                    refresh();
                },
                error: function (XMLHttpRequest) {
                    layer.close(index);
                    layer.alert('数据处理失败! 错误码:' + XMLHttpRequest.status, {title: '错误信息', icon: 2});
                }
            });
        });
    }

    function cancel(orderId) {
        layer.confirm('<div><div>输入取消订单原因</div><textarea class="textarea" id="content"></textarea></div>', {}, function (index) {
            var index = layer.load(3);
            var content = $("#content").val()
            console.log(orderId)
            $.ajax({
                type: 'post',
                url: './order/' + orderId + '/cancel',
                data:{
                    content:content
                },
                dataType: 'json',
                success: function (data) {
                    layer.close(index);
                    if (data.success != true) {
                        layer.alert(data.message, {title: '错误信息', icon: 2});
                        return;
                    }
                    layer.msg('取消成功!', {icon: 1, time: 1000});
                    // orderCount();
                    refresh();
                },
                error: function (XMLHttpRequest) {
                    layer.close(index);
                    layer.alert('数据处理失败! 错误码:' + XMLHttpRequest.status, {title: '错误信息', icon: 2});
                }
            });
        });
    }
    var logoBase64 = ""
    var orderId = ''
    var ORDERID = ''
    function bind_box(id) {
        orderId = id
        var index = layer.open({
            type: 2,
            title: '绑定冰包',
            content: 'bind-order',
            area:['500px','400px']
        });
    }
    function printTickets() {
        var cks = document.getElementsByName("checkbox");
        var count = 0, rowdatas=[]
        for (var i = 0; i < cks.length; i++) {
            if (cks[i].checked) {
                count++;
                var rowdata = table.row(i).data()
                rowdatas.push(rowdata)
            }
        }
        if (count == 0) {
            layer.msg('您还未勾选任何数据!', {icon: 5, time: 3000});
            return;
        }
        var divDom = document.createElement("select")
        divDom.setAttribute("id","printerSelect")
        divDom.setAttribute("size",1)
        CLODOP.Create_Printer_List(divDom);
        LODOP=getLodop();
        var Myprinter = new Printer()

        layer.confirm('<div><span>选择打印机</span>'+domToString(divDom)+'</div>',{},function(index){
            var printerIndex = $("#printerSelect").val()
            for (var i =0;i<rowdatas.length;i++){
                var rowdata = rowdatas[i]
                var imgBase64 = jrQrcode.getQrBase64(rowdata.orderId);
                var price = rowdata.medicineList[0].price.toFixed(2)
                var oreder = {
                    TradingHours:date(new Date().getTime()),
                    SerialNumber:rowdata.orderId,
                    Member:rowdata.receiverName,
                    ProductName:rowdata.medicineList[0].medicineName+'('+rowdata.medicineList[0].standard+')',
                    Name:rowdata.medicineList[0].name || "",
                    Manufacturer:rowdata.medicineList[0].manufacturer,
                    Exp:rowdata.medicineList[0].exp || "",
                    BatchNumber:rowdata.medicineList[0].batchNumber || "",
                    UnitPrice:price,
                    ConcessionalRate:price,
                    Number:rowdata.medicineList[0].num,
                    Total:rowdata.medicineList[0].num,
                    AmountMoney:rowdata.medicineList[0].num*price,
                    TotalMoney:rowdata.medicineList[0].num*price,
                    Receivable:rowdata.medicineList[0].num*price,
                    NetReceipts:rowdata.medicineList[0].num*price,
                    MedicalInsurance: '',
                    OutPocket:rowdata.medicineList[0].num*price,
                    Capitalize:number_chinese(rowdata.medicineList[0].num*price),
                    Collection:rowdata.medicineList[0].num*price,
                    GiveChange:'0.00',
                    Discount:'0.00',
                    Address:'长沙市岳麓区咸嘉湖路72号维安大药房',
                    Telephone:'0731-88612048',
                    imgSrc:imgBase64,
                }
                var docHtml  = Myprinter.getTemp(oreder)
                LODOP.PRINT_INIT("");
                LODOP.SET_PRINT_PAGESIZE(3,'80mm',0,"")
                // LODOP.SET_PRINT_STYLE("Bold",1);
                // LODOP.ADD_PRINT_TEXT(20,340,200,300,"药品签收单");
                LODOP.SET_PRINTER_INDEXA(printerIndex);
                LODOP.ADD_PRINT_HTM('4mm',0,'72mm','100%',docHtml);
                // LODOP.PREVIEW();
                LODOP.PRINT();
                updatePrintState(rowdata.orderId,1)

            }
            layer.close(index)
        });


    }
    function printReceipt(freezing) {
        var cks = document.getElementsByName("checkbox");
        var count = 0, rowdatas=[]
        for (var i = 0; i < cks.length; i++) {
            if (cks[i].checked) {
                count++;
                var rowdata = table.row(i).data()
                rowdatas.push(rowdata)
            }
        }
        if (count == 0) {
            layer.msg('您还未勾选任何数据!', {icon: 5, time: 3000});
            return;
        }
        var divDom = document.createElement("select")
        divDom.setAttribute("id","printerSelect")
        divDom.setAttribute("size",1)
        CLODOP.Create_Printer_List(divDom);
        LODOP=getLodop();
        var Myprinter = new Printer()
        console.log(logoBase64)
        layer.confirm('<div><span>选择打印机</span>'+domToString(divDom)+'</div>',{},function(index){
            var printerIndex = $("#printerSelect").val()
            for (var i =0;i<rowdatas.length;i++){
                var rowdata = rowdatas[i]
            var price = rowdata.medicineList[0].price.toFixed(2)

                var oreder = {
                    logoSrc:logoBase64,
                    OrderId:rowdata.orderId,
                    ProductName: rowdata.medicineList[0].medicineName,
                    BatchNumber: rowdata.medicineList[0].batchNumber,
                    Specifications: rowdata.medicineList[0].standard,
                    UnitPrice: price,
                    Number: rowdata.medicineList[0].num,
                    AmountMoney: rowdata.medicineList[0].num*price,
                    DeliveryTime: date(rowdata.reserveTime),
                    Address: rowdata.receiverAddress,
                    ReceivingName:rowdata.receiverName,
                    Contact: rowdata.receiverPhone,
                    Insurance:rowdata.insurance + rowdata.insuranceType,
                    Exp:rowdata.medicineList[0].exp || ""
                }
                var docHtml = ""
                if (freezing == 1){
                    docHtml = Myprinter.getColdReceiptTmp(oreder)
                }else {
                    docHtml = Myprinter.getNormalReceiptTmp(oreder)
                }
                LODOP.PRINT_INIT("");
                LODOP.SET_PRINT_PAGESIZE(1,'210mm','270mm',"A4");
                LODOP.SET_PRINT_STYLE("FontName","微软雅黑");
                LODOP.SET_PRINT_STYLE("FontSize",14);
                LODOP.ADD_PRINT_HTM('10mm', '1mm' ,'202mm', '260mm', docHtml);
                LODOP.SET_PRINTER_INDEXA(printerIndex);
                // LODOP.PREVIEW();
                LODOP.PRINT();
                updatePrintState(rowdata.orderId,2)
            }
            layer.close(index)
        });


    }

    function updatePrintState(id,state){
        $.ajax({
            url:"./order/print/update",
            method:"post",
            data:{
                orders:id,
                state:state
            },
            success(res){
                console.log(res)
            }
        })
    }
    function domToString (node) {
        var tmpNode = document.createElement('div')
        tmpNode.appendChild(node)
        var str = tmpNode.innerHTML
        tmpNode = node = null; // 解除引用，以便于垃圾回收
        return str;
    }
    function msgSuccess(content) {
        layer.msg(content, {icon: 1, time: 3000});
    }

    function number_chinese(str) {
        var num = parseFloat(str);
        var strOutput = "",
            strUnit = '仟佰拾亿仟佰拾万仟佰拾元角分';
        num += "00";
        var intPos = num.indexOf('.');
        if (intPos >= 0){
            num = num.substring(0, intPos) + num.substr(intPos + 1, 2);
        }
        strUnit = strUnit.substr(strUnit.length - num.length);
        for (var i=0; i < num.length; i++){
            strOutput += '零壹贰叁肆伍陆柒捌玖'.substr(num.substr(i,1),1) + strUnit.substr(i,1);
        }
        return strOutput.replace(/零角零分$/, '整').replace(/零[仟佰拾]/g, '零').replace(/零{2,}/g, '零').replace(/零([亿|万])/g, '$1').replace(/零+元/, '元').replace(/亿零{0,3}万/, '亿').replace(/^元/, "零元")

    }
</script>
<script>
</script>
</body>
</html>